<template>
  <div class="admin-dashboard">
    <div class="dashboard-header">
      <h1>管理仪表盘</h1>
      <p>欢迎回来，{{ authStore.user?.username }}</p>
    </div>

    <div class="stats-grid">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="40" color="#409EFF"><User /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.total_users || 0 }}</h3>
            <p>总用户数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="40" color="#67C23A"><Document /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.total_books || 0 }}</h3>
            <p>图书总数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="40" color="#E6A23C"><ShoppingCart /></el-icon>
          </div>
          <div class="stat-info">
            <h3>{{ stats.total_orders || 0 }}</h3>
            <p>订单总数</p>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon">
            <el-icon size="40" color="#F56C6C"><Money /></el-icon>
          </div>
          <div class="stat-info">
            <h3>¥{{ stats.total_revenue || 0 }}</h3>
            <p>总销售额</p>
          </div>
        </div>
      </el-card>
    </div>

    <div class="charts-row">
      <el-card class="chart-card">
        <template #header>
          <h3>销售趋势</h3>
        </template>
        <div ref="salesChart" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <h3>用户增长</h3>
        </template>
        <div ref="userChart" class="chart-container"></div>
      </el-card>
    </div>

    <div class="recent-activities">
      <el-card>
        <template #header>
          <h3>最近活动</h3>
        </template>
        <el-table :data="recentActivities" style="width: 100%">
          <el-table-column prop="action" label="操作" />
          <el-table-column prop="user" label="用户" />
          <el-table-column prop="timestamp" label="时间" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import * as echarts from 'echarts'
import api from '@/utils/api'

const authStore = useAuthStore()
const stats = ref({})
const recentActivities = ref([])
const salesChart = ref(null)
const userChart = ref(null)

let salesChartInstance = null
let userChartInstance = null

const loadDashboardData = async () => {
  try {
    const [statsResponse, activitiesResponse] = await Promise.all([
      api.get('/analytics/dashboard/'),
      api.get('/analytics/user-activity/?limit=10')
    ])
    
    stats.value = statsResponse.data
    recentActivities.value = activitiesResponse.data.results
    
    initCharts()
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

const initCharts = () => {
  if (salesChart.value) {
    salesChartInstance = echarts.init(salesChart.value)
    salesChartInstance.setOption({
      title: { text: '近7天销售额' },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: stats.value.sales_trend?.dates || []
      },
      yAxis: { type: 'value' },
      series: [{
        data: stats.value.sales_trend?.values || [],
        type: 'line',
        smooth: true
      }]
    })
  }

  if (userChart.value) {
    userChartInstance = echarts.init(userChart.value)
    userChartInstance.setOption({
      title: { text: '用户增长趋势' },
      tooltip: {},
      xAxis: {
        type: 'category',
        data: stats.value.user_growth?.dates || []
      },
      yAxis: { type: 'value' },
      series: [{
        data: stats.value.user_growth?.values || [],
        type: 'bar'
      }]
    })
  }
}

const handleResize = () => {
  salesChartInstance?.resize()
  userChartInstance?.resize()
}

onMounted(() => {
  loadDashboardData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  salesChartInstance?.dispose()
  userChartInstance?.dispose()
})
</script>

<style scoped>
.admin-dashboard {
  padding: 2rem;
}

.dashboard-header {
  margin-bottom: 2rem;
}

.dashboard-header h1 {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.dashboard-header p {
  color: #666;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stat-info h3 {
  font-size: 2rem;
  margin: 0;
  color: #333;
}

.stat-info p {
  margin: 0;
  color: #666;
}

.charts-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 300px;
}

.recent-activities {
  margin-top: 2rem;
}
</style>
